

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import { FoodRecord } from './types';
import { recordAPI, getAuthToken } from '../../services/api';

const RecordListPage: React.FC = () => {
  const navigate = useNavigate();
  const [selectedDate, setSelectedDate] = useState<string>('');
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false);
  const [currentDeleteRecordId, setCurrentDeleteRecordId] = useState<string | null>(null);
  const [foodRecords, setFoodRecords] = useState<FoodRecord[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>('');

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 今日饮食记录';
    return () => {
      document.title = originalTitle;
    };
  }, []);

  // 检查认证状态
  useEffect(() => {
    const token = getAuthToken();
    if (!token) {
      navigate('/login');
      return;
    }
  }, [navigate]);

  // 加载数据
  const loadRecords = async (date: string) => {
    try {
      setLoading(true);
      setError('');
      const records = await recordAPI.getRecords(date);
      
      // 转换API数据为前端格式
      const formattedRecords: FoodRecord[] = records.map((record: any) => ({
        id: record.id.toString(),
        foodName: record.food_name,
        portion: `${record.portion_value}${record.portion_unit}`,
        calories: record.calories * (record.portion_value / 100),
        protein: record.protein * (record.portion_value / 100),
        carb: record.carb * (record.portion_value / 100),
        fat: record.fat * (record.portion_value / 100),
        time: new Date(record.created_at).toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        }),
        image: '' // 暂时留空
      }));
      
      setFoodRecords(formattedRecords);
    } catch (err: any) {
      setError(err.message || '加载记录失败');
      console.error('加载记录失败:', err);
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    setSelectedDate(today);
    loadRecords(today);
  }, []);

  // 计算总计
  const calculateTotal = () => {
    const totalCalories = foodRecords.reduce((sum, record) => sum + record.calories, 0);
    const totalProtein = foodRecords.reduce((sum, record) => sum + record.protein, 0);
    const totalCarb = foodRecords.reduce((sum, record) => sum + record.carb, 0);
    const totalFat = foodRecords.reduce((sum, record) => sum + record.fat, 0);

    return {
      calories: totalCalories,
      protein: totalProtein,
      carb: totalCarb,
      fat: totalFat
    };
  };

  const totals = calculateTotal();

  // 处理搜索
  const handleSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      navigate('/food-search');
    }
  };

  // 处理日期变化
  const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newDate = e.target.value;
    setSelectedDate(newDate);
    loadRecords(newDate);
  };

  // 处理编辑记录
  const handleEditRecord = (recordId: string) => {
    console.log('编辑记录:', recordId);
    navigate(`/food-detail?recordId=${recordId}`);
  };

  // 处理删除记录
  const handleDeleteRecord = (recordId: string) => {
    setCurrentDeleteRecordId(recordId);
    setShowDeleteModal(true);
  };

  // 确认删除
  const handleConfirmDelete = async () => {
    if (currentDeleteRecordId) {
      try {
        await recordAPI.deleteRecord(parseInt(currentDeleteRecordId));
        // 重新加载数据
        loadRecords(selectedDate);
        showToast('删除成功');
      } catch (err: any) {
        showToast('删除失败: ' + err.message);
        console.error('删除记录失败:', err);
      }
    }
    setShowDeleteModal(false);
    setCurrentDeleteRecordId(null);
  };

  // 取消删除
  const handleCancelDelete = () => {
    setShowDeleteModal(false);
    setCurrentDeleteRecordId(null);
  };

  // 显示提示信息
  const showToast = (message: string) => {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = 'fixed top-20 right-6 bg-secondary text-white px-6 py-3 rounded-lg shadow-lg z-50';
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
      if (toast.parentNode) {
        toast.parentNode.removeChild(toast);
      }
    }, 3000);
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 bg-white border-b border-border-light h-16 z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <i className="fas fa-utensils text-white text-sm"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">食算</h1>
          </div>
          
          {/* 全局搜索框 */}
          <div className="flex-1 max-w-md mx-8">
            <div className="relative">
              <input 
                type="text" 
                placeholder="搜索食物..." 
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                onKeyPress={handleSearchKeyPress}
                className="w-full pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
            </div>
          </div>
          
          {/* 右侧操作区 */}
          <div className="flex items-center space-x-4">
            {/* 消息通知 */}
            <button className="relative p-2 text-text-secondary hover:text-primary">
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
            </button>
            
            {/* 用户头像和下拉菜单 */}
            <div className="relative">
              <button className="flex items-center space-x-2 p-1 rounded-lg hover:bg-gray-100">
                <img 
                  src="https://s.coze.cn/image/0i6UaB78fbA/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                />
                <span className="text-sm text-text-primary">张三</span>
                <i className="fas fa-chevron-down text-xs text-text-secondary"></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 左侧菜单 */}
      <aside className={`fixed left-0 top-16 bottom-0 w-60 bg-white border-r border-border-light z-40 ${styles.sidebarTransition}`}>
        <nav className="p-4">
          <ul className="space-y-2">
            <li>
              <Link to="/home" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-home text-lg"></i>
                <span className="font-medium">首页</span>
              </Link>
            </li>
            <li>
              <Link to="/food-search" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-search text-lg"></i>
                <span className="font-medium">食物搜索</span>
              </Link>
            </li>
            <li>
              <Link to="/record-list" className={`${styles.navItem} ${styles.navItemActive} flex items-center space-x-3 px-4 py-3 rounded-lg`}>
                <i className="fas fa-list text-lg"></i>
                <span className="font-medium">饮食记录</span>
              </Link>
            </li>
            <li>
              <Link to="/history" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-history text-lg"></i>
                <span className="font-medium">历史记录</span>
              </Link>
            </li>
            <li>
              <Link to="/settings" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-cog text-lg"></i>
                <span className="font-medium">设置</span>
              </Link>
            </li>
          </ul>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main className="ml-60 mt-16 p-6 min-h-screen">
        {/* 页面头部 */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h2 className="text-2xl font-bold text-text-primary">今日饮食记录</h2>
            <nav className="flex items-center space-x-2 text-sm text-text-secondary mt-1">
              <span>首页</span>
              <i className="fas fa-chevron-right text-xs"></i>
              <span>饮食记录</span>
            </nav>
          </div>
          <div className="flex items-center space-x-4">
            {/* 日期选择器 */}
            <div className="flex items-center space-x-2">
              <i className="fas fa-calendar text-text-secondary"></i>
              <input 
                type="date" 
                value={selectedDate}
                onChange={handleDateChange}
                className="border border-border-light rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
            </div>
            {/* 快速添加食物按钮 */}
            <Link 
              to="/food-search"
              className="bg-primary text-white px-6 py-2 rounded-lg hover:bg-indigo-600 transition-colors flex items-center space-x-2"
            >
              <i className="fas fa-plus"></i>
              <span>添加食物</span>
            </Link>
          </div>
        </div>

        {/* 饮食记录表格 */}
        <section className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border-light">
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">食物名称</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">份量</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">卡路里</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">蛋白质(g)</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">碳水(g)</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">脂肪(g)</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">记录时间</th>
                  <th className="text-left py-3 px-4 font-semibold text-text-primary">操作</th>
                </tr>
              </thead>
              <tbody>
                {foodRecords.map(record => (
                  <tr key={record.id} className={`${styles.tableRow} border-b border-border-light`}>
                    <td className="py-4 px-4">
                      <div className="flex items-center space-x-3">
                        <img 
                          src={record.image} 
                          alt={record.foodName} 
                          className="w-10 h-10 rounded-lg object-cover"
                        />
                        <span className="font-medium text-text-primary">{record.foodName}</span>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-text-secondary">{record.portion}</td>
                    <td className="py-4 px-4 text-text-primary font-medium">{record.calories}</td>
                    <td className="py-4 px-4 text-text-secondary">{record.protein}</td>
                    <td className="py-4 px-4 text-text-secondary">{record.carb}</td>
                    <td className="py-4 px-4 text-text-secondary">{record.fat}</td>
                    <td className="py-4 px-4 text-text-secondary">{record.time}</td>
                    <td className="py-4 px-4">
                      <div className="flex space-x-2">
                        <button 
                          className={`${styles.editBtn} ${styles.actionBtn} p-2 border border-border-light rounded-lg text-text-secondary hover:border-blue-500`}
                          onClick={() => handleEditRecord(record.id)}
                        >
                          <i className="fas fa-edit"></i>
                        </button>
                        <button 
                          className={`${styles.deleteBtn} ${styles.actionBtn} p-2 border border-border-light rounded-lg text-text-secondary hover:border-red-500`}
                          onClick={() => handleDeleteRecord(record.id)}
                        >
                          <i className="fas fa-trash"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          {/* 当日总计 */}
          <div className="mt-6 pt-6 border-t border-border-light">
            <div className="flex items-center justify-between">
              <div className="text-lg font-semibold text-text-primary">当日总计</div>
              <div className="grid grid-cols-4 gap-8 text-right">
                <div>
                  <div className="text-sm text-text-secondary">卡路里</div>
                  <div className="text-lg font-semibold text-text-primary">{totals.calories.toLocaleString()} kcal</div>
                </div>
                <div>
                  <div className="text-sm text-text-secondary">蛋白质</div>
                  <div className="text-lg font-semibold text-text-primary">{totals.protein.toFixed(1)}g</div>
                </div>
                <div>
                  <div className="text-sm text-text-secondary">碳水</div>
                  <div className="text-lg font-semibold text-text-primary">{totals.carb.toFixed(1)}g</div>
                </div>
                <div>
                  <div className="text-sm text-text-secondary">脂肪</div>
                  <div className="text-lg font-semibold text-text-primary">{totals.fat.toFixed(1)}g</div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>

      {/* 删除确认对话框 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
          <div className="bg-white rounded-2xl p-6 max-w-md w-full mx-4">
            <div className="text-center">
              <div className="w-16 h-16 bg-danger bg-opacity-10 rounded-full flex items-center justify-center mx-auto mb-4">
                <i className="fas fa-trash text-danger text-2xl"></i>
              </div>
              <h3 className="text-lg font-semibold text-text-primary mb-2">确认删除</h3>
              <p className="text-text-secondary mb-6">确定要删除这条饮食记录吗？此操作无法撤销。</p>
              <div className="flex space-x-3">
                <button 
                  onClick={handleCancelDelete}
                  className="flex-1 px-4 py-2 border border-border-light rounded-lg text-text-secondary hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button 
                  onClick={handleConfirmDelete}
                  className="flex-1 px-4 py-2 bg-danger text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default RecordListPage;

